package com.xd.core.product.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xd.common.constant.SysConstant;
import com.xd.common.exception.XkdException;
import com.xd.core.product.dto.ProductDto;
import com.xd.core.product.entity.Product;
import com.xd.core.product.entity.ProductCompany;
import com.xd.core.product.mapper.ProductCompanyMapper;
import com.xd.core.product.mapper.ProductMapper;
import com.xd.core.product.service.IProductService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xd.core.product.vo.ProductVo;
import com.xd.core.product.vo.ProductVo1;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author ZX
 * @since 2025-02-23
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements IProductService {
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductCompanyMapper productCompanyMapper;

    @Override
    public Page<ProductVo> productList(ProductDto dto) {
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return (Page<ProductVo>) productMapper.getProductList(dto);
    }

    @Override
    public List<ProductVo1> getProductVoList(Integer companyId) {
        List<ProductCompany> productCompanies =productCompanyMapper.selectProductCompanies(companyId);
        List<Integer> productIds = productCompanies.stream().map(ProductCompany::getProductId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(productIds)){
            throw new XkdException("该资方下没有配置产品");
        }
        List<Product> list = list(new LambdaQueryWrapper<Product>()
                .eq(Product::getStatus, SysConstant.PRODUCT_ENABLE)
                .in(Product::getProductId, productIds));

        list.forEach(product -> {
            String typeDesc = translateProductType(product.getType());
            product.setTypeRemark(typeDesc);
        });
        return BeanUtil.copyToList(list, ProductVo1.class);
    }
    private String translateProductType(String typeCode) {
        switch (typeCode) {
            case "0":
                return "消费信贷";
            case "1":
                return "车抵贷";
            case "2":
                return "房抵贷";
            case "3":
                return "经营贷";
            default:
                return "未知类型";
        }
    }
}
